// 定义数据结构接口，增强代码可维护性
interface IExchangeItem {
  id: number;
  name: string;
  category: string;
  description: string;
  pointsRequired: number; // 单个所需积分
  ratio: string; // 兑换比例文字说明
  limit: number | null; // 可兑换次数, 0表示无限, null表示已兑完
}

interface IHistoryRecord {
  itemName?: string; // 兑换的物品名
  source?: string;   // 收入来源
  points: number;
  time: string;
}

Page({
  data: {
    userPoints: 9850, // 用户当前积分
    rate: 100, // 积分与人民币的兑换比例
    itemList: [] as IExchangeItem[], // 可兑换商品列表

    // 弹窗控制
    showDetailsPopup: false,
    showExchangePopup: false,

    // 明细弹窗
    activeTab: 0,
    exchangeHistory: [] as IHistoryRecord[],
    incomeHistory: [] as IHistoryRecord[],

    // 兑换弹窗
    currentTargetItem: {} as IExchangeItem, // 当前操作的兑换项
    exchangeQuantity: 1, // 兑换数量
    isSubmitting: false, // 是否正在提交兑换（防止重复点击）
  },

  onLoad() {
    this.fetchInitialData();
  },

  // 模拟从服务器获取初始数据
  fetchInitialData() {
    // 实际项目中，这里应该是 wx.request 请求
    const mockItemList: IExchangeItem[] = [
      { id: 1, name: '1元红包', category: '现金红包', description: '直接兑换成微信红包', pointsRequired: 100, ratio: '1:100', limit: 5 },
      { id: 2, name: '5元红包', category: '现金红包', description: '超值兑换，限时供应', pointsRequired: 500, ratio: '1:100', limit: 2 },
      { id: 3, name: '会员周卡', category: '虚拟商品', description: '享受7天平台会员权益', pointsRequired: 2000, ratio: '1:2000', limit: 0 },
      { id: 4, name: '精美周边', category: '实物商品', description: '平台限定版纪念品', pointsRequired: 12000, ratio: '1:12000', limit: 1 },
    ];

    const mockExchangeHistory: IHistoryRecord[] = [
      { itemName: '1元红包', points: 100, time: '2023-10-26 10:30' },
    ];

    const mockIncomeHistory: IHistoryRecord[] = [
      { source: '每日签到', points: 20, time: '2023-10-27 08:00' },
      { source: '任务奖励', points: 150, time: '2023-10-26 14:00' },
    ];

    this.setData({
      itemList: mockItemList,
      exchangeHistory: mockExchangeHistory,
      incomeHistory: mockIncomeHistory,
    });
  },

  // --- 交互事件处理 ---

  // 点击“兑换明细”
  onViewDetails() {
    console.log(1)
    this.setData({ showDetailsPopup: true });
  },

  // 关闭明细弹窗
  onCloseDetailsPopup() {
    this.setData({ showDetailsPopup: false });
  },

  // 明细弹窗Tab切换
  onTabChange(event: WechatMiniprogram.CustomEvent) {
    console.log(event.detail.value)
    this.setData({ activeTab: event.detail.value });
  },

  // 点击商品“兑换”按钮
  onClickExchange(event: WechatMiniprogram.TouchEvent) {
    const item = event.currentTarget.dataset.item as IExchangeItem;
    this.setData({
      currentTargetItem: item,
      exchangeQuantity: 1, // 重置为默认值1
      showExchangePopup: true,
    });
  },

  // 关闭兑换弹窗
  onCloseExchangePopup() {
    this.setData({
      showExchangePopup: false,
      isSubmitting: false // 确保关闭时重置加载状态
    });
  },

  // 监听兑换数量输入
  onQuantityChange(event: WechatMiniprogram.CustomEvent) {
    let quantity = Number(event.detail);
    // 基础校验，防止输入负数或0
    if (quantity < 1) {
      quantity = 1;
    }
    this.setData({ exchangeQuantity: quantity });
  },

  // 提交兑换请求
  handleSubmitExchange() {
    const { userPoints, currentTargetItem, exchangeQuantity } = this.data;
    const totalCost = currentTargetItem.pointsRequired * exchangeQuantity;

    // 前端校验
    if (totalCost > userPoints) {
      wx.showToast({ title: '松果币余额不足', icon: 'none' });
      return;
    }
    if (currentTargetItem.limit !== 0 && exchangeQuantity > currentTargetItem.limit!) {
      wx.showToast({ title: '超出剩余兑换次数', icon: 'none' });
      return;
    }

    this.setData({ isSubmitting: true });

    // 模拟API请求
    wx.showLoading({ title: '兑换中...', mask: true });

    setTimeout(() => {
      wx.hideLoading();

      // 1. 更新前端数据（本地临时更新）
      const newPoints = userPoints - totalCost;
      const newRecord: IHistoryRecord = {
        itemName: currentTargetItem.name,
        points: totalCost,
        time: this.formatTime(new Date()),
      };

      // 更新商品列表中的限制次数
      const newItemList = this.data.itemList.map(item => {
        if (item.id === currentTargetItem.id && item.limit !== 0) {
          // 如果 limit 是 null 或 undefined，则不处理
          if (item.limit) {
            item.limit -= exchangeQuantity;
          }
        }
        return item;
      });

      this.setData({
        userPoints: newPoints,
        exchangeHistory: [newRecord, ...this.data.exchangeHistory],
        itemList: newItemList,
        isSubmitting: false,
        showExchangePopup: false,
      });

      // 2. 弹出成功提示
      wx.showToast({
        title: '兑换成功！',
        icon: 'none', // 统一使用 'none' 类型
        duration: 2000,
      });

    }, 1000); // 模拟1秒网络延迟
  },

  // 工具函数：格式化时间
  formatTime(date: Date): string {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()

    return `${[year, month, day].map(this.formatNumber).join('-')} ${[hour, minute].map(this.formatNumber).join(':')}`
  },

  formatNumber(n: number): string {
    const s = n.toString()
    return s[1] ? s : '0' + s
  }
});
